package io.kiki.sba.registry.server.metadata.remoting.connection;


import io.kiki.sba.registry.common.model.Node.NodeType;
import io.kiki.sba.registry.server.metadata.bootstrap.config.NodeConfig;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * Handle meta node's connect request
 */
public class MetaConnectionManager extends AbstractNodeConnectManager {

    @Autowired
    private NodeConfig nodeConfig;

    @Override
    public Collection<InetSocketAddress> getChannelRemoteAddressList(String dataCenter) {
        // get all address, the dataCenter arg is ignored
        Collection<InetSocketAddress> channelRemoteAddressList = super.getChannelRemoteAddressList(dataCenter);
        if (channelRemoteAddressList.isEmpty()) {
            return Collections.emptyList();
        }
        List<InetSocketAddress> list = new ArrayList<>();
        for (InetSocketAddress inetSocketAddress : channelRemoteAddressList) {
            String ipAddress = inetSocketAddress.getAddress().getHostAddress();
            String dc = nodeConfig.getCentralControlDataCenter(ipAddress);
            if (dataCenter.equals(dc)) {
                list.add(inetSocketAddress);
            }
        }
        return list;
    }

    @Override
    protected int getServerPort() {
        return serverConfig.getMetaServerPort();
    }

    @Override
    public NodeType getConnectNodeType() {
        return NodeType.central_control;
    }
}
